package com.hallowd.purcom;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;



public class StuffActivity extends Activity {

    Button homeButton;
    Button mSaveButton;
    EditText mDescription;
    EditText mName;
    EditText mAmountRequested;
    EditText mDueDate;
    EditText mLocation;
    Activity activity;
    String communityID;
    private DatePickerDialog toDatePickerDialog;
    private SimpleDateFormat dateFormatter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stuff);
        Bundle extras = getIntent().getExtras();
        activity=this;
        communityID = extras.getString("communityID");
        mAmountRequested = (EditText) findViewById(R.id.reqAmountEdit);
        mDescription = (EditText) findViewById(R.id.descrpEdit);
        mName = (EditText) findViewById(R.id.nameEditText);
        mDueDate = (EditText) findViewById(R.id.dateEdit);
        mLocation = (EditText) findViewById(R.id.locationEdit);
        homeButton = (Button) findViewById(R.id.homeButton);
        homeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, wellcomePageActivity.class);
                startActivity(intent);
            }
        });

        mSaveButton = (Button) findViewById(R.id.saveButton);
        mSaveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                (new StuffActivityAsyncTask()).execute();
            }
        });
        dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
        setDateTimeField();

    }
    private void setDateTimeField() {
        mDueDate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                toDatePickerDialog.show();
            }
        });


        Calendar newCalendar = Calendar.getInstance();

        toDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                mDueDate.setText(dateFormatter.format(newDate.getTime()));
            }

        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_stuff, menu);
        return true;
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class StuffActivityAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params)  {
            String url = "http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/community/"+communityID+"/stuff/new";
            String amountRequested = mAmountRequested.getText().toString();
            String name = mName.getText().toString();
            String description = mDescription.getText().toString();
            String datetime = mDueDate.getText().toString();
            String location = mLocation.getText().toString();
            Timestamp timestamp=null;

            if(datetime!=null && !datetime.isEmpty()){
                try{

                    Date parsedDate = dateFormatter.parse(datetime);
                    timestamp = new java.sql.Timestamp(parsedDate.getTime());
                }catch(Exception e){
                    //this generic but you csan control another types of exception
                    timestamp=null;
                }
            }



           // url = url + "?communityName=" + communityName + "&description=" + description;
            Log.d("", url);

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost request = new HttpPost(url);
            request.addHeader("Content-Type","application/json");
            request.addHeader("Accept","application/json");
            Integer amountContributed = 0;

            Long userId = null;
            SharedPreferences pref = getApplicationContext().getSharedPreferences("purcomPref", MODE_PRIVATE);
            userId = pref.getLong("userID",-1L);


            try {
                JSONObject stuff = new JSONObject();
                stuff.put("amountRequested", amountRequested);
                stuff.put("amountContributed", 0);
                stuff.put("name", name);
                stuff.put("description", description);
                stuff.put("location", location);
                stuff.put("datetime",  timestamp.getTime());
                stuff.put("communityid", communityID);
                JSONObject b = new JSONObject();
                b.put("stuff",stuff);
                b.put("userID",userId);
                String  json = b.toString();
                StringEntity se = new StringEntity(json);

                request.setEntity(se);

                HttpResponse response = httpclient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                    for (String line = null; (line = reader.readLine()) != null; ) {
                        builder.append(line).append("\n");
                    }

                    Log.d("", "Create Stuff " + builder.toString());
                    return builder.toString();
                }
                else {
                    Log.d("", "Create Stuff Failed");
                }
            } catch (Exception e) {
                Log.d("", e.toString());
                Log.d("", e.getCause().toString());
                Log.d("", "Connection problem occured");
            }

            return null;
        }

        protected void onPostExecute(String result) {
            AlertDialog.Builder builder = new AlertDialog.Builder(StuffActivity.this);
            builder.setMessage("You successfully created stuff!")
                    .setTitle("CreateStuff Result")
                    .setPositiveButton(android.R.string.ok, null);
            AlertDialog dialog = builder.create();
            dialog.show();
            Intent myintent = new Intent(activity,wellcomePageActivity.class);
            startActivity(myintent);
        }
    }
}
